import pytest
from src.pages.login_page.login_page import LoginPage
import json
import os
from pathlib import Path
from package_for_test.utl.langchain_agent import ElementAgent
from src.utils.scrape_and_save import scrape_and_save


@pytest.mark.skip
class TestLogin:
    current_path = Path(__file__).resolve().parent.parent
    element_file = current_path / 'config' / 'login_page_element_locators.json'
    url = 'https://team.pescms.com/?g=Team&m=Login&a=index&back_url=Lw=='

    def test_successful_login(self, page, login_url, logger):

        if os.path.exists(TestLogin.element_file):
            element_locators = json.load(open(TestLogin.element_file, encoding='utf-8'))
            login_page = LoginPage(page, element_locators)
            new_dom = scrape_and_save(page, TestLogin.url, 'new_login_page')
            old_dom_file = TestLogin.current_path / 'config' / 'page_content_data' / 'login_page.html'
            if os.path.exists(old_dom_file):
                with open(old_dom_file, 'r', encoding='utf-8') as f:
                    old_dom_data = f.read()
            ElementAgent(page_name='login_page', new_dom_data_path=new_dom, old_dom_data=old_dom_data).call_model()
            login_page.login(username='demo', password='111')
            cookies = page.content().cookies(login_url)
            with open(TestLogin.current_path / 'config' / 'cookies.json', 'w', encoding='utf-8') as f:
                f.write(cookies)
        else:
            login_page = LoginPage(page)
            page.goto(TestLogin.url)
            new_dom = scrape_and_save(page, TestLogin.url, 'login_page')
            ElementAgent(page_name='login_page', new_dom_data_path=new_dom, old_dom_data=None).call_model()
            # 传入新生成的locators数据
            login_page.locators_data = json.load(open(TestLogin.element_file, encoding='utf-8'))
            # 给实例传入新的locators数据
            login_page.set_locators(login_page.locators_data)
            print(login_page.login_button)
            login_page.login(username='demo', password='111')


if __name__ == '__main__':
    pytest.main()
